package jalus.blog;

import jalus.Action;
import jalus.service.ConfigureService;
import jalus.service.PostService;
import jalus.utils.HttpUtils;
import jalus.utils.MyUtils;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sun.syndication.feed.synd.SyndContent;
import com.sun.syndication.feed.synd.SyndContentImpl;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndEntryImpl;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.feed.synd.SyndFeedImpl;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.SyndFeedOutput;

public class FeedServlet extends Action{
	private static final String MIME_TYPE = "application/xml; charset=UTF-8";
	private static final String DEFAULT_FEED_TYPE = "rss_2.0";
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)	throws IOException {
		
		String host = ConfigureService.getInstance().getHost();
		
		String tag = req.getParameter("tag");
		String feedTitle = ConfigureService.getInstance().getBlogTitle();

		PostService postService = PostService.getInstance();
		List<jalus.pojo.Post> postList;
		postList = postService.getPostListByOffsetAndTag(tag, null, ConfigureService.getInstance().getFeedCount());
		if(tag != null){
			feedTitle = feedTitle + " Tag:" + tag;
		}
		MyUtils.processPostList(postList);
		List<SyndEntry> feedEntryList = new ArrayList<SyndEntry>(ConfigureService.getInstance().getFeedCount()); 
		for(jalus.pojo.Post post : postList){
			SyndEntry feedEntry = new SyndEntryImpl();
			feedEntry.setTitle(post.getTitle());
			feedEntry.setAuthor(post.getAuthor().getNickname());
			feedEntry.setLink(HttpUtils.connectUrl(host, "/blog/post?action=view&postid=") + post.getId());
			feedEntry.setPublishedDate(post.getDate());
			SyndContent description = new SyndContentImpl();
			description.setValue(post.getContent());
			feedEntry.setDescription(description);
			feedEntryList.add(feedEntry);
		}
		
		SyndFeed feed = new SyndFeedImpl();
		feed.setFeedType(DEFAULT_FEED_TYPE);
		//关于feed 的描述
		feed.setTitle(feedTitle);
		feed.setLink(host);
		feed.setDescription("Rss feed 2.0 powered by Rome.");
		feed.setPublishedDate(new Date());
		feed.setEntries(feedEntryList);
		
        resp.setCharacterEncoding("utf-8"); 
        resp.setContentType(MIME_TYPE);
        PrintWriter out = resp.getWriter();
   	 	SyndFeedOutput output = new SyndFeedOutput();
   	 	try {
			output.output(feed, out);
		} catch (FeedException e) {
			e.printStackTrace();
		}
        out.flush();
	}
	
}
